interface SensorDataBuffer {
  data: number[]; // 改为普通数组
  time: string[];
  length: number;
}

interface ProcessedData {
  type: string;
  sensorType: string;
  data: number[];
  time: string[];
  chartId?: number;
}

// 传感器数据缓冲区
const sensorBuffers: { [key: string]: SensorDataBuffer } = {
  uvc: { data: [], time: [], length: 0 },
  tem: { data: [], time: [], length: 0 },
  hum: { data: [], time: [], length: 0 },
  pre: { data: [], time: [], length: 0 },
  inf: { data: [], time: [], length: 0 }
};

let maxLength = 10;
let maxLengthZoomed = 300;
let isZoomed = false;
let currentZoomedSensor: string | null = null;
let throttleInterval = 100;
let isThrottleMode = false;
let lastUpdateTime = 0;
const UPDATE_THROTTLE = 50;

let isTransitioning = false; // 是否处于设备切换的过渡状态
const INITIAL_BATCH_SIZE = 1; // 初始数据批处理大小，用于平滑启动
let initialBatch: any[] = []; // 存储初始数据的临时数组

// 逐帧渲染优化相关变量
let frameUpdateQueue: any[] = []; // 帧更新队列
let isProcessingFrame = false; // 是否正在处理帧
// const FRAME_BATCH_SIZE = 1; // 每帧处理的数据点数量（逐点渲染）

// 逐帧处理紫外数据的函数已移除，直接在WebSocket处理逻辑中实现

// 处理帧队列的函数
function processFrameQueue() {
  if (frameUpdateQueue.length === 0) {
    isProcessingFrame = false;
    return;
  }

  isProcessingFrame = true;

  // 每次只处理一小部分数据，实现逐点渲染的效果
  const batchSize = Math.max(1, Math.floor(frameUpdateQueue.length / 10)); // 动态调整批大小
  const batch = frameUpdateQueue.splice(0, batchSize);
  const dataBatch = batch.map(p => p.value);
  const timeBatch = batch.map(p => p.time);
  
  if (batch.length > 0) {
    // 在紫外放大模式下，不包含毫秒
    const formattedTime = formatTimeData(timeBatch, 'uvc', true);
    self.postMessage({
      type: 'chart_update_frame',
      chartId: 1, // 紫外线图表ID
      sensorType: 'uvc',
      data: dataBatch,
      time: formattedTime,
      isFrameUpdate: true,
      timestamp: Date.now()
    });
  }

  if (frameUpdateQueue.length > 0) {
    requestAnimationFrame(processFrameQueue);
  } else {
    isProcessingFrame = false;
  }
}

// 数据处理函数
function addDataToBuffer(sensorType: string, values: number[], baseTime: Date | any) {

  const buffer = sensorBuffers[sensorType];
  if (!buffer) return;

  const currentMaxLength = isZoomed ? maxLengthZoomed : maxLength;
  
  if (sensorType === 'uvc') {
    // 紫外线传感器：批量处理多个数据点
    values.forEach((value, index) => {
      const time = new Date(baseTime.getTime() + index * 100);
      buffer.data.push(value || 0);
      buffer.time.push(time.toISOString());

      buffer.length++;
    });
    
    // 紫外线超过容量时，删除前面的10个数据点
    if (buffer.length > currentMaxLength) {
      const deleteCount = Math.min(10, buffer.length - currentMaxLength + 10);
      buffer.data.splice(0, deleteCount);
      buffer.time.splice(0, deleteCount);
      buffer.length -= deleteCount;
    }
  } else {
     // 其他传感器（红外、温度、湿度、压力）：单个数据点处理
    values.forEach((value, index) => {
      const time = new Date(baseTime.getTime() + index * 100).toISOString();
      buffer.data.push(value || 0);
      buffer.time.push(time);
      buffer.length++;
      // 超过容量时，删除最旧的一个数据点（FIFO队列）
      if (buffer.length > currentMaxLength) {
        buffer.data.shift();
        buffer.time.shift();
        buffer.length--;
      }
   
    });
  }
}

// 获取缓冲区数据的副本
function getBufferData(sensorType: string): { data: number[], time: string[] } {
  const buffer = sensorBuffers[sensorType];
  if (!buffer) return { data: [], time: [] };
  const formattedData = Array.from(buffer.data.slice(0, buffer.length)).map(value => {
    const num = Number(value);
    return isNaN(num) ? 0 : parseFloat(num.toFixed(2));
  });
  return {
    data: formattedData,
    time: [...buffer.time.slice(0, buffer.length)]
  };
}

// 清理所有缓冲区
function resetAllBuffers() {
  Object.values(sensorBuffers).forEach(buffer => {
    buffer.data.length = 0; // 修复：清空数据数组
    buffer.time.length = 0;
    buffer.length = 0;
  });
  // --- 修改的代码：激活过渡状态 ---
  isTransitioning = true;
  initialBatch = [];
  // --- 修改结束 ---
}

// 格式化时间显示
function formatTimeData(timeArray: string[], sensorType?: string, includeMilliseconds = true): string[] {
  return timeArray.map(timeStr => {
    const date = new Date(timeStr);
    const baseTime = date.toLocaleTimeString('zh-CN', { hour12: false, hour: '2-digit', minute: '2-digit', second: '2-digit' });
    // 紫外线传感器保持毫秒精度，其他传感器只显示到秒
    if (sensorType === 'uvc' && includeMilliseconds) {
      return baseTime + '.' + date.getMilliseconds().toString().padStart(3, '0');
    } else {
      return baseTime;
    }
  });
}

self.addEventListener('message', function(e) {
  const { type, rawData, deviceId, gatewayIp, isZoomed: messageIsZoomed, initialData } = e.data;
  switch (type) {
    case 'process_websocket_data':
      try {
        const data = JSON.parse(rawData);
        if (data.action === 'sendData') {
          const { ID, gatewayIp: msgGatewayIp, data: sensorData } = data;
          if (msgGatewayIp === gatewayIp) {
            self.postMessage({ type: 'device_flash', deviceId: ID });

            if (ID === deviceId) {
              const now = Date.now();
              const currentThrottle = isThrottleMode ? throttleInterval : UPDATE_THROTTLE;
              if (now - lastUpdateTime < currentThrottle && !isTransitioning) {
                return;
              }
              lastUpdateTime = now;

              const [tem, hum, pre, inf, ...uvcs] = sensorData;
              const baseTime = new Date();

              // --- 新增代码：处理过渡状态，收集初始数据 ---
              if (isTransitioning) {
                initialBatch.push({ tem, hum, pre, inf, uvcs, baseTime });

                if (initialBatch.length >= INITIAL_BATCH_SIZE) {
                  // 当收集到足够的数据后，一次性处理并发送
                  initialBatch.forEach(batchItem => {
                    addDataToBuffer('uvc', batchItem.uvcs, batchItem.baseTime);
                    addDataToBuffer('tem', [batchItem.tem], batchItem.baseTime);
                    addDataToBuffer('hum', [batchItem.hum], batchItem.baseTime);
                    addDataToBuffer('pre', [batchItem.pre], batchItem.baseTime);
                    addDataToBuffer('inf', [batchItem.inf], batchItem.baseTime);
                  });

                  const allSensorsData = {
                    type: 'all_charts_update_batch',
                    data: {
                      uvc: getBufferData('uvc'),
                      tem: getBufferData('tem'),
                      hum: getBufferData('hum'),
                      pre: getBufferData('pre'),
                      inf: getBufferData('inf')
                    },
                    timeFormatted: {
                      uvc: formatTimeData(getBufferData('uvc').time, 'uvc'),
                      tem: formatTimeData(getBufferData('tem').time, 'tem'),
                      hum: formatTimeData(getBufferData('hum').time, 'hum'),
                      pre: formatTimeData(getBufferData('pre').time, 'pre'),
                      inf: formatTimeData(getBufferData('inf').time, 'inf')
                    }
                  };
                  self.postMessage(allSensorsData);

                  // 恢复正常模式
                  isTransitioning = false;
                  initialBatch = [];
                }
                return; // 在过渡状态下，不执行后续的单次更新逻辑
              }

              if (messageIsZoomed && currentZoomedSensor) {
                // 放大模式下只更新对应的传感器数据，减少不必要的计算
                if (currentZoomedSensor === 'uvc') {
                  // 使用逐帧渲染处理紫外数据
                  uvcs.forEach((value: number, index: number) => {
                    const timestamp = new Date(baseTime.getTime() + index * 100).toISOString();
                    frameUpdateQueue.push({
                      sensorType: 'uvc',
                      value: value,
                      time: timestamp
                    });
                  });
                  
                  // 如果没有正在处理帧，开始处理
                  if (!isProcessingFrame) {
                    isProcessingFrame = true;
                    processFrameQueue();
                  }
                  return;
                } else if (currentZoomedSensor === 'tem') {
                  addDataToBuffer('tem', [tem], baseTime);
                  const temData = getBufferData('tem');
                  self.postMessage({ type: 'chart_update', chartId: 3, sensorType: 'tem', data: temData.data, time: formatTimeData(temData.time, 'tem') });
                  return;
                } else if (currentZoomedSensor === 'hum') {
                  addDataToBuffer('hum', [hum], baseTime);
                  const humData = getBufferData('hum');
                  self.postMessage({ type: 'chart_update', chartId: 4, sensorType: 'hum', data: humData.data, time: formatTimeData(humData.time, 'hum') });
                  return;
                } else if (currentZoomedSensor === 'pre') {
                  addDataToBuffer('pre', [pre], baseTime);
                  const preData = getBufferData('pre');
                  self.postMessage({ type: 'chart_update', chartId: 5, sensorType: 'pre', data: preData.data, time: formatTimeData(preData.time, 'pre') });
                  return;
                } else if (currentZoomedSensor === 'inf') {
                  addDataToBuffer('inf', [inf], baseTime);
                  const infData = getBufferData('inf');
                  self.postMessage({ type: 'chart_update', chartId: 2, sensorType: 'inf', data: infData.data, time: formatTimeData(infData.time, 'inf') });
                  return;
                }
              }

              // 正常模式下的批量更新
              addDataToBuffer('uvc', uvcs, baseTime);
              addDataToBuffer('tem', [tem], baseTime);
              addDataToBuffer('hum', [hum], baseTime);
              addDataToBuffer('pre', [pre], baseTime);
              addDataToBuffer('inf', [inf], baseTime);

              const allSensorsData = {
                type: 'all_charts_update_batch',
                data: {
                  uvc: getBufferData('uvc'),
                  tem: getBufferData('tem'),
                  hum: getBufferData('hum'),
                  pre: getBufferData('pre'),
                  inf: getBufferData('inf')
                },
                timeFormatted: {
                  uvc: formatTimeData(getBufferData('uvc').time, 'uvc'),
                  tem: formatTimeData(getBufferData('tem').time, 'tem'),
                  hum: formatTimeData(getBufferData('hum').time, 'hum'),
                  pre: formatTimeData(getBufferData('pre').time, 'pre'),
                  inf: formatTimeData(getBufferData('inf').time, 'inf')
                }
              };
              self.postMessage(allSensorsData);
            }
          }
        } else if(data.action === "repeateConnect") {
            // 重连请求
            if (data && data.data) {
              this.self.postMessage({
                type: "repeateConnect",
                data: data.data
              });
            } 
        }
      } catch (error) {
        console.error('Worker数据处理错误:', error);
        self.postMessage({ type: 'worker-error', error: error instanceof Error ? error.message : String(error) });
      }
      break;

    case 'reset':
      resetAllBuffers();
      // 清理逐帧渲染状态
      frameUpdateQueue = [];
      isProcessingFrame = false;
      break;

    case 'process_initial_data':
      if (initialData && Array.isArray(initialData)) {
        initialData.forEach(item => {
          const baseTime = new Date(`2025/8/23 ${item.time}`);
          const uvcValues = item.uvc.split(',').map(Number);

          addDataToBuffer('uvc', uvcValues, baseTime);
          addDataToBuffer('tem', [parseFloat(item.tem)], baseTime);
          addDataToBuffer('hum', [parseFloat(item.hum)], baseTime);
          addDataToBuffer('pre', [parseFloat(item.pre)], baseTime);
          addDataToBuffer('inf', [parseFloat(item.inf)], baseTime);
        });

        const allSensorsData = {
          type: 'all_charts_update_batch',
          data: {
            uvc: getBufferData('uvc'),
            tem: getBufferData('tem'),
            hum: getBufferData('hum'),
            pre: getBufferData('pre'),
            inf: getBufferData('inf')
          },
          timeFormatted: {
            uvc: formatTimeData(getBufferData('uvc').time, 'uvc'),
            tem: formatTimeData(getBufferData('tem').time, 'tem'),
            hum: formatTimeData(getBufferData('hum').time, 'hum'),
            pre: formatTimeData(getBufferData('pre').time, 'pre'),
            inf: formatTimeData(getBufferData('inf').time, 'inf')
          }
        };
        self.postMessage(allSensorsData);
      }
      break;

    // ... 其他 case 保持不变 ...
    case 'updateConfig':
      maxLength = e.data.maxLength || 10;
      maxLengthZoomed = e.data.maxLengthZoomed || 300;
      break;
      
    case 'setZoomMode':
      isZoomed = e.data.isZoomed || false;
      currentZoomedSensor = e.data.zoomedSensor || null;
      const targetLength = isZoomed ? maxLengthZoomed : maxLength;
      
      // 清理逐帧渲染队列
      frameUpdateQueue = [];
      isProcessingFrame = false;
      
      Object.values(sensorBuffers).forEach(buffer => {
        if (buffer.length > targetLength) {
          const excess = buffer.length - targetLength;
          // 修复：正确处理数组截取
          buffer.data.splice(0, excess);
          buffer.time.splice(0, excess);
          buffer.length = targetLength;
        }
      });

      // 清理完了之后要立刻发送一次数据过去触发更新
      const allSensorsData = {
        type: 'all_charts_update_batch',
        data: {
          uvc: getBufferData('uvc'),
          tem: getBufferData('tem'),
          hum: getBufferData('hum'),
          pre: getBufferData('pre'),
          inf: getBufferData('inf')
        },
        timeFormatted: {
          uvc: formatTimeData(getBufferData('uvc').time, 'uvc'),
          tem: formatTimeData(getBufferData('tem').time, 'tem'),
          hum: formatTimeData(getBufferData('hum').time, 'hum'),
          pre: formatTimeData(getBufferData('pre').time, 'pre'),
          inf: formatTimeData(getBufferData('inf').time, 'inf')
        }
      };
      self.postMessage(allSensorsData);
      break;
      
    case 'heartbeat':
      self.postMessage({ type: 'heartbeat-reply' });
      break;
      
    case 'setThrottleMode':
      isThrottleMode = e.data.enabled;
      throttleInterval = isThrottleMode ? 500 : 100;
      break;
  }
});

self.addEventListener('error', (error) => {
  console.error('Worker error:', error);
  self.postMessage({ type: 'worker-error', error: error.message });
});

export type { ProcessedData, SensorDataBuffer };